package org.pskovgu.pskovbus;

import java.io.FileOutputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.app.ProgressDialog;

public class MainActivity extends Activity implements TextWatcher {
	private StationDataSource stationDS;
	private PointDataSource pointDS;
	int direction = 0;
	TextView messageView;
	TextView waitView;
	ListView timetableListView;
	AutoCompleteTextView busstopTextView;
	ProgressBar progressBarView;
	ProgressDialog mProgressDialog;
	Station currentStation;
	List<Bus> buses;
	ArrayAdapter<Bus> busAdapter;
	AlertDialog.Builder ad;
	String rgHost = "http://rghost.ru/download/42376838/cc8ecbfb156ed75334adf11836dda32073e516c4/buses";
	
	List<Point> points;
	ArrayAdapter<Point> pointAdapter;
	private boolean continueNormalStart;
	
	//final int DIALOG_UPDATE = 1;
	
	private class DownloadFile extends AsyncTask<String, Integer, String> {
		
		@Override
	    protected void onPreExecute() {
	        super.onPreExecute();
	        mProgressDialog.show();
	    }
		
		@Override
		 protected void onPostExecute(String result) {
		  // TODO Auto-generated method stub
			super.onPostExecute(result);
			mProgressDialog.dismiss();
			if (result == "true")
			{
				initializeDB();
			}
		 }
		

	    @Override
	    protected void onProgressUpdate(Integer... progress) {
	        super.onProgressUpdate(progress);
	        mProgressDialog.setProgress(progress[0]);
	    }
		
	    @Override
	    protected String doInBackground(String... sUrl) {
	        try {
	            URL url = new URL(sUrl[0]);
	            URLConnection connection = url.openConnection();
	            connection.connect();
	            // this will be useful so that you can show a typical 0-100% progress bar
	            int fileLength = connection.getContentLength();

	            // download the file
	            InputStream input = new BufferedInputStream(url.openStream());
	            OutputStream output = new FileOutputStream("/data/data/org.pskovgu.pskovbus/databases/buses");

	            byte data[] = new byte[1024];
	            long total = 0;
	            int count;
	            while ((count = input.read(data)) != -1) {
	                total += count;
	                // publishing the progress....
	                publishProgress((int) (total * 100 / fileLength));
	                output.write(data, 0, count);
	            }

	            output.flush();
	            output.close();
	            input.close();
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
	        return "true";
	    }
	}
	
	
	
	public class backgroundLoadListView extends
	  AsyncTask<Void, Void, Void> {

	 @Override
	 protected void onPostExecute(Void result) {
	  // TODO Auto-generated method stub
		 progressBarView.setVisibility(View.GONE);
		 waitView.setVisibility(View.GONE);
		 timetableListView.setVisibility(View.VISIBLE);
		 updateListView();
	 }

	 @Override
	 protected void onPreExecute() {
	  // TODO Auto-generated method stub
	  progressBarView.setVisibility(View.VISIBLE);
	  waitView.setVisibility(View.VISIBLE);
	  timetableListView.setVisibility(View.GONE);
	 }

	 @Override
	 protected Void doInBackground(Void... params) {
	  // TODO Auto-generated method stub
	  populateListView();
	  return null;
	 }

	}
	
	
	
	
	
	
	

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mProgressDialog = new ProgressDialog(MainActivity.this);
        mProgressDialog.setMessage("Загрузка расписания...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        
        
		String title = "Обновление расписания";
		String message = "Вы хотите загрузить обновление (~400 Кб)?";
		String button1String = "Загрузить";
		String button2String = "Отмена";
		
		continueNormalStart = true;
		
		ad = new AlertDialog.Builder(this);
		ad.setTitle(title);  
		ad.setMessage(message);
		ad.setPositiveButton(button1String, new OnClickListener() {
			public void onClick(DialogInterface dialog, int arg1) {
				DownloadFile downloadFile = new DownloadFile();
				downloadFile.execute(rgHost);
				continueNormalStart = false;
			}
		});
		ad.setNegativeButton(button2String, new OnClickListener() {
			public void onClick(DialogInterface dialog, int arg1) {
				;
			}
		});
		ad.setCancelable(true);
		
		ad.show();
        
        messageView = (TextView) findViewById(R.id.messageView);
        waitView = (TextView) findViewById(R.id.waitView);
        progressBarView = (ProgressBar) findViewById(R.id.progressBar1);
        
        timetableListView = (ListView) findViewById(R.id.timetableListView);
        
        timetableListView.setVisibility(View.INVISIBLE); 
        busstopTextView = (AutoCompleteTextView) findViewById(R.id.busstopTextView);
        
        
        
        final Button btnSwapDirection = (Button) findViewById(R.id.swapdirection);
        btnSwapDirection.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                direction = (direction==0) ? 1 : 0;
                //populateListView();
                new backgroundLoadListView().execute();
            }
        });
        
        if (continueNormalStart)
        {        
        	initializeDB();
        }
        
       
    }

	private void initializeDB() {
		stationDS = new StationDataSource(this);        
        pointDS = new PointDataSource(this);
		if ((busstopTextView!=null) && (pointDS!=null) && (stationDS!=null))
        {
        	stationDS.open();
            List<Station> stations = stationDS.getAllStations();
            stationDS.close();
        
        
        busstopTextView.addTextChangedListener(this);
        ArrayAdapter<Station> stationAdapter = new ArrayAdapter<Station>(this, android.R.layout.simple_dropdown_item_1line, stations);
        busstopTextView.setAdapter(stationAdapter);
        busstopTextView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				currentStation = (Station)arg0.getItemAtPosition(arg2);
				//populateListView();
				new backgroundLoadListView().execute();
				
			}
        	
		});
        }
	}
    
    public void updateListView()
    {
    	if (points.isEmpty())
		{
			messageView.setVisibility(View.VISIBLE);
		}
		else
		{
			messageView.setVisibility(View.GONE);
		}
    	if (pointAdapter!=null)
    	{
    	     timetableListView.setAdapter(pointAdapter);
    	     pointAdapter.notifyDataSetChanged();
    	     timetableListView.invalidateViews();
    	}
    }
    
    public void populateListView()
    {
    	if ((pointDS!=null) && (currentStation!=null))
    	{    		      
            pointDS.open();
            points = pointDS.getPointsByStationId((int)currentStation.getId(), direction);
            pointDS.close();
            pointAdapter = new ArrayAdapter<Point>(this, android.R.layout.simple_list_item_1, points); 			
    	}
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		
	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
		
	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}
}
